<?php
require_once '../wp-config.php';
require_once '../wp-settings.php';

function ext($file)
{
    $exp = explode(".", $file);
    return $exp[count($exp) - 1];
}

//Connessione database
$db = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME);


function sup($val)
{
    if ($val <= 80)
        return "30>80";
    if ($val <= 100)
        return "81>100";
    if ($val <= 130)
        return "101>130";
    if ($val <= 160)
        return "131>160";
    if ($val <= 200)
        return "161>200";

    return ">200";
}
function getRegione($regione)
{
    global $db;
    try {
        $sql = "SELECT comuni.ID as comune, provincie.ID as provincia, regioni.ID as regione FROM `comuni` INNER JOIN provincie ON comuni.IDProvincia = provincie.ID INNER JOIN regioni ON provincie.IDRegione = regioni.ID WHERE comuni.`Testo` LIKE '" . $regione . "'";
        $r = mysql_fetch_array(mysql_query($sql, $db));
        return $r['regione'];
    }
    catch (Exception $e) {
        return $r['regione'];
    }
}
function getProvincia($regione)
{
    global $db;
    try {
        $sql = "SELECT comuni.ID as comune, provincie.ID as provincia, regioni.ID as regione FROM `comuni` INNER JOIN provincie ON comuni.IDProvincia = provincie.ID INNER JOIN regioni ON provincie.IDRegione = regioni.ID WHERE comuni.`Testo` LIKE '" . $regione . "'";
        $r = mysql_fetch_array(mysql_query($sql, $db)) or (0);
        return $r['provincia'];
    }
    catch (Exception $e) {
        return $r['provincia'];
    }
}
function getComune($regione)
{
    global $db;
    try {
        $sql = "SELECT comuni.ID as comune, provincie.ID as provincia, regioni.ID as regione FROM `comuni` INNER JOIN provincie ON comuni.IDProvincia = provincie.ID INNER JOIN regioni ON provincie.IDRegione = regioni.ID WHERE comuni.`Testo` LIKE '" . $regione . "'";
        $r = mysql_fetch_array(mysql_query($sql, $db)) or (0);
        return $r['comune'];
    }

    catch (Exception $e) {
        return $r['comune'];
    }
}

function sanitize($text)
{
    $text = str_replace("", "", $text);
    $s = array("è", "è", "à", "ì", "ò");
    $r = array("&egrave;", "&egrave;", "&agrave;", "&igrave;", "&ograve;");
    return $text;
}

if(!function_exists("appthemes_filter")){
	function appthemes_filter($text) {
		$text = strip_tags($text);
		$text = trim($text);
		$char_limit = 5000;
		if( strlen($text) > $char_limit ) {
			$text = substr($text, 0, $char_limit);
		}
		return $text;
	}
}


function getZip($location)
{
    $var = $location->Placemark[0]->AddressDetails->Country->AdministrativeArea;
    $var = $var->SubAdministrativeArea->Locality->PostalCode->PostalCodeNumber;
    return $var;
}
function getCitta($location)
{
    $var = $location->Placemark[0]->AddressDetails->Country->AdministrativeArea;
    $var = $var->SubAdministrativeArea->Locality->LocalityName;
    global $db;
    try {
        $sql = "SELECT comuni.ID as comune, provincie.ID as provincia, regioni.ID as regione FROM `comuni` INNER JOIN provincie ON comuni.IDProvincia = provincie.ID INNER JOIN regioni ON provincie.IDRegione = regioni.ID WHERE comuni.`Testo` LIKE '" . $var . "'";
        $r = mysql_fetch_array(mysql_query($sql, $db)) or (0);
        return $r['comune'];
    }

    catch (Exception $e) {
        return $r['comune'];
    }
    return $var;
}
function getLocal($location)
{
    $var = $location->Placemark[0]->AddressDetails->Country->AdministrativeArea;
    $var = $var->SubAdministrativeArea->Locality->DependentLocality->DependentLocalityName;
    return $var;
}
function getStreet($location)
{
    $var = $location->Placemark[0]->AddressDetails->Country->AdministrativeArea;
    $var = $var->SubAdministrativeArea->Locality->Thoroughfare->ThoroughfareName;
    return $var;
}
//Verifica se esiste già
function alreadyExist($id){
	global $db;
	$sql = "SELECT COUNT(ID) AS tot,ID FROM wp_posts WHERE IDXML = '$id'";
	$r = mysql_fetch_array(mysql_query($sql,$db));
	if($r['tot'] == 0)
		return -1;
	return $r['ID'];
}

$var = $_POST;

//Codifica ID diversi
function id_scs2cii($id_scservizi){
	global $db;
	$sql = "SELECT ID_C FROM traduzioneScservizi WHERE ID_S = $id_scservizi";
	$r = mysql_fetch_array(mysql_query($sql,$db));
	echo mysql_error();
	$id_casa_in_italia = $r['ID_C'];
	return $id_casa_in_italia;
}

$idXML = "sc-" . $var['id'];
$user_id = id_scs2cii($var['idAzienda']);

//Accessori
$accessori = "";

if(trim($var['disponibileDa']) != "")
	$accessori .= "Disponibile da: " . $var['disponibileDa'] . "\n";

if(trim($var['annoRis']) != "")
	$accessori .= "Ristrutturato il: ". $var['annoRis'] . "\n";

if(trim($var['annoCost']) != "")
	$accessori .= "Costruito nel: ". $var['annoCost'] . "\n";

if(trim($var['mobili']) != "")
	$accessori .= "Mobili: ". $var['mobili'] . "\n";

if(trim($var['piano']) != "")
	$accessori .= "Piano n&deg; : ". $var['piano'] . "\n";

if(trim($var['nLocali']) != "")
	$accessori .= "Numero di locali: ". $var['nLocali'] . "\n";

if(trim($var['Riscaldamento']) != "")
	$accessori .= "Riscaldamento: ". $var['Riscaldamento'] . " " . $var['RiscaldamentoTipo'] . " " . $var['RiscaldamentoAlim'] . "\n";

if(trim($var['soggiorno']) != "")
	$accessori .= "Soggiorno: ". $var['soggiorno'] . "\n";

if(trim($var['cucina']) != "")
	$accessori .= "Cucina: ". $var['cucina'] . "\n";

if(trim($var['giardino']) != "")
	$accessori .= "Giardino: ". $var['giardino'] . "\n";

if(trim($var['cortile']) != "")
	$accessori .= "Cortile: ". $var['cortile'] . "\n";

if(trim($var['ascensore']) != 0)
	$accessori .= "Ascensore: presente\n";

if(trim($var['balconi']) != 0)
	$accessori .= "Balconi: presenti\n";

if(trim($var['cantina']) != 0)
	$accessori .= "Cantina: presente\n";

if(trim($var['taverna']) != 0)
	$accessori .= "Taverna: presente\n";

if(trim($var['lavanderia']) != 0)
	$accessori .= "Lavanderia: presente\n";

if(trim($var['camino']) != 0)
	$accessori .= "Camino: presente\n";

if(trim($var['fotovoltaico']) != 0)
	$accessori .= "Impianto fotovoltaico: presente\n";

if(trim($var['domotica']) != 0)
	$accessori .= "Domotica: presente\n";

if(trim($var['imp_cert']) != 0)
	$accessori .= "Certificazione impianti: presente\n";

if(trim($var['finiture']) != 0)
	$accessori .= "Finiture: Si\n";


if(trim($var['esposizione']) != "")
	$accessori .= "Esposizione: ". $var['esposizione'] . "\n";

if(trim($var['youtube']) != "")
	$accessori .= "youtube: ". $var['youtube'] . "\n";

if(trim($var['ariaCondizionata']) != "")
	$accessori .= "Aria condizionata: presente\n";


//Foto


function name($url){
	$exp = explode("/", $url);
	$name = $exp[count($exp) -1];
	$ext = ext($name);
	return str_replace($ext, strtolower($ext) , $name);
}

for($i = 0;$i < 5;$i++) {
	$img = $var['foto' . $i];
	if(trim($img) == "http://")
		continue;
	fwrite(fopen("./uploads/scservizi/" . name($img), 'w+'), file_get_contents($img));
}

    // Gmap Area
  $key = "NO-KEY- :)";
    $json = "&output=json&sensor=true_or_false&key=";
    $url = "http://maps.google.com/maps/geo?q=";

    $lon = $var['lon'];
    $lat = $var['lat'];
    $maps_url = $url . $lat . "," . $lon . $json . $key;
    $location = json_decode(file_get_contents($maps_url));
    // End GMap area

    $advals['cp_accessori'] = $accessori;

    $advals['cp_accessori'] = nl2br($advals['cp_accessori']);

    $advals['cat'] = 3;
    $cat = (int) $advals['cat'];
    $advals['regione'] = getRegione($citta);
    $regione = (int)$advals['regione'];
    $advals['province'] = getProvincia($citta);
    $province = (int)$advals['province'];
    $advals['comuni'] = getComune($citta);
    $comuni = (int)$advals['comuni'];
    $advals['post_title'] = $titolo;   //----------------------------------------
    $advals['cp_tipologia'] = "";
    $advals['cp_localit'] = $var['zona'];
    $advals['cp_street'] = getStreet($location);
    $advals['cp_zipcode'] = getZip($location);
    $zip = $advals['cp_zipcode'];
    $advals['cp_affitto'] = $var['tipoVendita'];
    $tipo = strtolower($advals['cp_affitto']);
    $advals['cp_numero_letti'] = $var['nCamere'];
    $letti = (int)$advals['cp_numero_letti'];
 	$advals['cp_numero_bagni'] = $var['nBagni'];
 	$bagni = (int)$advals['cp_numero_bagni'];
    $advals['cp_price'] = $var['prezzo'];
    $prezzo = (int)$advals['cp_price'];
    $advals['cp_superficie'] = sup($var['mq']);

    $advals['cp_garage'] = $var['postoAuto'];


    $advals['post_content'] = sanitize($var['descrizione']);
    $advals['cp_cls'] = "";
    $cls = $advals['cp_cls'];
    $advals['tags_input'] = "";
    $advals['cp_coupon_code'] = "3MESIGRATIS";
    $advals['catname'] = 3;
    $advals['user_id'] = $user_id;
    $advals['cp_sys_ad_listing_fee'] = "10.00";
    $advals['cp_coupon_type'] = "%";
    $advals['cp_coupon'] = "100.00";
    $advals['cp_sys_total_ad_cost'] = "0.00";
    $time = mktime();
    $time = $time + (3*30*24*60*60);

    $advals['cp_sys_expire_date'] = date("d/m/Y H:i:s",$time);//"07/30/2011 17:53:02";

    //Metodo di classipress
    $ad_length = 90;
    $advals['cp_sys_expire_date'] = date_i18n('m/d/Y H:i:s', strtotime('+' . $ad_length . ' days'));

    $advals['cp_sys_ad_duration'] = "90";
    $tipologia = 0;

    $new_ad = array();
    $new_ad['post_title'] = $advals['post_title'];
    $new_ad['post_content'] = trim($advals['post_content']);
    $new_ad['post_status'] = "publish"; //cp_set_post_status($advals);
    $new_ad['post_author'] = $advals['user_id'];
    $new_ad['post_type'] = 'ad_listing'; //array

    //Esiste già?
    $id_exist = alreadyExist($idXML);
	if($id_exist != -1){
		$new_ad['ID'] = $id_exist;
	}

    // make sure the WP sanitize_post function doesn't strip out embed & other html
    // print_r($new_ad).' <- new ad array<br>';
    // insert the new ad
    $post_id = wp_insert_post($new_ad);

	//set the custom post type categories
	wp_set_post_terms( $post_id, appthemes_filter($advals['cat']), 'ad_cat', false);

    foreach($advals as $meta_key => $meta_value) {
        if (appthemes_str_starts_with($meta_key, 'cp_'))
            add_post_meta($post_id, $meta_key, $meta_value, true);
    }

    $advals['post_content'] = $gt->query($translate, $advals['post_content']);
    $post_id_en = wp_insert_post_en($advals);
    $bagni = 0;
    $sql = "UPDATE wp_posts SET comment_status = 'closed', IDXML = '$idXML', IDEn = $post_id_en, CLS = '" . $cls . "', tipo = '" . $tipo . "', Regione = " . $regione . " ,Provincia = " . $province . ",Comune =" . $comuni .
    ", Superficie = '" . $superficie . "' ,Prezzo = " . $prezzo . ",Bagni = " . $bagni . ",Letti = " . $letti . ",ZIP = '" . $zip . "', Categoria = $cat , Tipologia = '" . $tipologia . "' WHERE ID = $post_id";

    mysql_query($sql, $db) OR die(mysql_error() . $sql);

    // Attachment

for($i = 0;$i < 5;$i++) {
	$img = $var['foto' . $i];
	$filename = "./uploads/scservizi/" . name($img);

	if (!file_exists($filename))
		break;
	$filename = str_replace("/uploads","" , $filename);
	$wp_filetype = wp_check_filetype(basename($filename), null);
	$attachment = array(
	    'post_mime_type' => $wp_filetype['type'],
	    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
	    'post_content' => '',
	    'post_status' => 'inherit'
	    );
	$attach_id = wp_insert_attachment($attachment, $filename, $post_id);
	// you must first include the image.php file
	// for the function wp_generate_attachment_metadata() to work
	require_once("../wp-admin" . '/includes/image.php');
	$filename = "./uploads/scservizi/" . name($img);
	$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
	wp_update_attachment_metadata($attach_id, $attach_data);
}

echo "ok";
    // DEBUG IN CASE OF ERROR
    /*	echo "ID: " .$idXML;
   echo "<br>";
   echo "ID WP: " . $post_id;
   echo "<br>" . $titolo;
   echo "<hr>";
*/



?>